﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.ServiceModel.Activation;
using System.Web.Routing;
using COFE.IO;
using COFE.IO.FSI;
using System.Net;
using System.ServiceModel.Web;
using COFE.IO.FSIEX;
using COFE.IO.SZ;
using SevenZip;
using COFE.Web.Services.Properties;
//using System.Data.SQLite;
using System.Data;
using COFE.Data;
using COFE.Core;

namespace COFE.Web.Services
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            SevenZipExtractor.SetLibraryPath(Settings.Default.DllPath7z);
            COFEShared.EnablePlugin(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"));

            RegisterDBUsers(); //This will be removed when a UI is available.
            RegisterRoutes(RouteTable.Routes);
        }

        void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();

        }

        private void RegisterDBUsers()
        {
            COFEShared.VolumeRegistrar.RegisterVolume("FSI", "TEMP", @"path=C:\TEMP\Demo", Core.Profile.VolumeAccessMode.All);
            COFEShared.VolumeRegistrar.RegisterVolume("SZ", "SZ", Core.Profile.VolumeAccessMode.All);

            IUserProfile userProfile = null;

            if (!DBUserProfile.Exists("Test"))
            {
                userProfile = DBUserProfile.Create("Test", "Test");
                Console.WriteLine("Create");
            }
            else userProfile = DBUserProfile.Login("Test", "Test");
            Console.WriteLine("Login");

            if (!userProfile.Volumes.PrimaryVolumes.Any(v => v.ListerKey == "TEMP"))
                userProfile.RegisterVolume("TEMP");
            userProfile.RegisterVolume("SZ");
            COFEShared.AdminUserProfile.TryParsePath("{TEMP}");
        }

        private void RegisterRoutes(RouteCollection routes)
        {
            //Web services - xml and json
            routes.Add(new ServiceRoute("search", new WebServiceHostFactory(), typeof(SearchServices)));
            routes.Add(new ServiceRoute("entries", new WebServiceHostFactory(), typeof(EntryServices)));
            routes.Add(new ServiceRoute("entrytypes", new WebServiceHostFactory(), typeof(EntryTypeServices)));
            routes.Add(new ServiceRoute("lookup", new WebServiceHostFactory(), typeof(LookupServices)));
            routes.Add(new ServiceRoute("users", new WebServiceHostFactory(), typeof(UserServices)));
            routes.Add(new ServiceRoute("events", new WebServiceHostFactory(), typeof(EventServices)));
            routes.Add(new ServiceRoute("contents", new WebServiceHostFactory(), typeof(EntryServices)));
        }
    }
}